//
//  EFAMsgUpdateVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/10/31.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAMsgUpdateVC.h"
#import <MJRefresh.h>
#import <UIScrollView+EmptyDataSet.h>
#import "ApiManager.h"
#import "GlobalHeader.h"
#import "EFAModel.h"
#import "UIColor+XDHex.h"
#import "EFAMsgSelVersionVC.h"

@interface EFAMsgUpdateVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) UIBarButtonItem *saveBarBtnItem;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
@property (strong, nonatomic) EFADevVersionItem *versionItem;
@property (strong, nonatomic) EFACompanyCodeItem *companyItem;
@property (strong, nonatomic) EFAUsageCodeItem *usageItem;
@property (strong, nonatomic) EFADevVersionItem *updateVersion;
@end
static NSString *const kReuseCellId = @"UITableViewCell";
@implementation EFAMsgUpdateVC
#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    self.navigationItem.title = @"升级信息";
    self.navigationItem.rightBarButtonItem = self.saveBarBtnItem;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)initSubViews {
    //    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    //    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    // 下拉刷新
    //    self.tableView.mj_header = self.mj_header;
    //    self.tableView.mj_footer = self.mj_footer;
    
    //    [self.tableView.mj_header beginRefreshing];
    [self requestDeviceVersionWithHeader:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"没有数据" attributes:dic];
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"global_empty"];
}
//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    return self.versionItem ? self.cfgModel.efairydevicesetting_thv_list.count + 2 : 0;
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kReuseCellId];
        cell.textLabel.font = [UIFont systemFontOfSize:14.0];
        cell.textLabel.textColor = [UIColor xd_colorWithHex:EFAGlobalColorFontDarkBlack];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:14.0];
        cell.detailTextLabel.textColor = [UIColor xd_colorWithHex:EFAGlobalColorFontMidBlack];
//        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
//    NSArray *value = @[[NSString stringWithFormat:@"%ldS", (long)self.cfgModel.efairydevicesetting_heartbeat_interval],
//                       [NSString stringWithFormat:@"%@", self.cfgModel.efairydevicesetting_audio_on ? @"正常" : @"静音"]];
//    if (indexPath.row < value.count) {
//        cell.textLabel.text = self.titleArray[indexPath.row];
//        cell.detailTextLabel.text = value[indexPath.row];
//    } else {
//        NSInteger index = indexPath.row - value.count;
//        if (index < self.cfgModel.efairydevicesetting_thv_list.count) {
//            EFADevRealTimeDataItem *item = self.cfgModel.efairydevicesetting_thv_list[index];
//            cell.textLabel.text = [NSString stringWithFormat:@"%@通道%ld报警阈值", item.cidTitle, (long)item.cid];
//            cell.detailTextLabel.text = item.thvValue;
//        }
//    }
    
    if (indexPath.section == 0) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        if (indexPath.row == 0) {
            cell.textLabel.text = @"当前软件版本";
            cell.detailTextLabel.text = self.versionItem.efairydeviceversion_version;
        } else if (indexPath.row == 1) {
            cell.textLabel.text = @"企业名称";
            cell.detailTextLabel.text = self.versionItem.efairydevicecompanycode_name;
        } else if (indexPath.row == 2) {
            cell.textLabel.text = @"用途";
            cell.detailTextLabel.text = self.versionItem.efairydeviceusagecode_name;
        }
    } else if (indexPath.section == 1) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        if (indexPath.row == 0) {
            cell.textLabel.text = @"选择企业名称";
            cell.detailTextLabel.text = self.companyItem.efairydevicecompanycode_name;
        } else if (indexPath.row == 1) {
            cell.textLabel.text = @"选择用途";
            cell.detailTextLabel.text = self.usageItem.efairydeviceusagecode_name;
        } else if (indexPath.row == 2) {
            cell.textLabel.text = @"选择版本";
            cell.detailTextLabel.text = self.updateVersion.efairydeviceversion_version;
        }
    }
    
//    if (indexPath.row == 0) {
//        cell.textLabel.text = @"当前软件版本";
//        cell.detailTextLabel.text = self.versionItem.efairydeviceversion_version;
//    } else if (indexPath.row == 1) {
//        cell.textLabel.text = @"选择将要升级的版本";
//        cell.detailTextLabel.text = self.updateVersion ? self.updateVersion.efairydeviceversion_version : @"";
//    }
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5.9;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {           // 选择企业名称
            [self jumpToSelectCompany];
        } else if (indexPath.row == 1) {    // 选择用途
            [self jumpToSelectUsage];
        } else if (indexPath.row == 2) {    // 选择版本
            [self jumpToSelectVersion];
        }
    }
}

#pragma mark - event response
- (void)saveBarBtnTapped:(UIBarButtonItem *)item {
    if (!self.updateVersion) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请选择要升级的版本"];
        return;
    }
    
    if (self.successHandle) {
        self.successHandle(self.updateVersion);
        self.successHandle = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - private methods
- (void)jumpToSelectCompany {
    EFAMsgSelVersionVC *vc = [[EFAMsgSelVersionVC alloc] initWithViewType:EFAMsgSelVersionVCTypeCompany];
    vc.successHandle = ^(id versionItem) {
        self.companyItem = versionItem;
        [self refreshWholeView];
    };
    [self showViewController:vc sender:nil];
}
- (void)jumpToSelectUsage {
    EFAMsgSelVersionVC *vc = [[EFAMsgSelVersionVC alloc] initWithViewType:EFAMsgSelVersionVCTypeUsage];
    vc.successHandle = ^(id versionItem) {
        self.usageItem = versionItem;
        [self refreshWholeView];
    };
    [self showViewController:vc sender:nil];
}
- (void)jumpToSelectVersion {
    if (!self.companyItem) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请选择企业名称"];
        return;
    }
    if (!self.usageItem) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请选择用途"];
        return;
    }
    
    EFAMsgSelVersionVC *vc = [[EFAMsgSelVersionVC alloc] initWithViewType:EFAMsgSelVersionVCTypeVersion];
    vc.efairydevicecompanycode_id = self.companyItem.efairydevicecompanycode_id;
    vc.efairydeviceusagecode_id = self.usageItem.efairydeviceusagecode_id;
    vc.successHandle = ^(EFADevVersionItem *versionItem) {
        self.updateVersion = versionItem;
        [self refreshWholeView];
    };
    [self showViewController:vc sender:nil];
}
- (void)refreshWholeView {
    //    // 尾部加载更多的显示
    //    if (self.userList.totalLoad) {
    //        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    //    } else {
    //        [self.tableView.mj_footer resetNoMoreData];
    //    }
    
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    [self requestDeviceVersionWithHeader:isHeader];
}

#pragma mark - network request
- (void)requestDeviceVersionWithHeader:(BOOL)isHeader {
    // 需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairydevice_id" : @(self.device_id)};
    NSLog(@"请求设备版本的参数：%@", pars);
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiDeviceVersion] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求设备版本返回：%@", responseObject);
        [hud hideAnimated:YES];
        self.versionItem = [EFADevVersionItem yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求设备配置失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

#pragma mark - getters and setters
- (UIBarButtonItem *)saveBarBtnItem {
    if (!_saveBarBtnItem) {
        _saveBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveBarBtnTapped:)];
        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_saveBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
        NSDictionary * disableBarItemAtt = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen alpha:0.5],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_saveBarBtnItem setTitleTextAttributes:disableBarItemAtt forState:UIControlStateDisabled];
    }
    return _saveBarBtnItem;
}

- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}
@end
